<?php
/**
 * API模块 公共的控制器
 * User: sunlight
 * Date: 2018/11/21
 * Time: 17:43
 */

namespace app\api\controller;

use think\Controller;
use app\common\lib\Aes;
use app\common\lib\IAuth;
use app\common\lib\Time;
use app\common\lib\exception\ApiException;
use app\common\lib\exception\ApiHandleException;
use think\Cache;

class Common extends Controller{

    /**
     * headers信息
     * @var string
     */
    public $headers='';

    public $page=1;
    public $size=10;
    public $from=0;

    /**
     * 初始化方法
     */
    public function _initialize() {
        $this->checkRequestAuth();
        //$this->testAes();
    }

    /**
     * 检查每次app请求的数据是否合法
     */
    public function checkRequestAuth(){
        //首先需要获取headers
        $headers=request()->header();
        //todo

       //基础参数校验
        if (empty($headers['sign'])){
            throw new ApiException('sign不存在', 400);
        }
        /*var_dump($headers);exit;
        if (!in_array($headers['app_type'],config('app.apptypes'))){
            throw new ApiException('app_type不合法', 400);
        }*/

        //需要sign
        if(!IAuth::checkSignPass($headers)){
            throw new ApiException('授权码sign失败', 401);
        }

        Cache::set($headers['sign'],1,config('app.app_sign_cache_time'));

        // 1、文件  2、mysql 3、redis
        $this->headers = $headers;
    }

    //测试sign
    public function testAes(){
        $data=[
            'did' => '123456dg',
            'version' => 1,
            'time' => Time::get13TimeStamp(),
        ];

        //$str='FMyCkGsFlHaWfM6HOaFoh7qe5YPbBfuhlYBcB6GCr4g=';
        //新6vL18D6iPb3iQur+7qG8p6Cs3hgkLDv49UBPeP4U5TeKWhGICSXQKLzSaF5m728R
        echo IAuth::setSign($data);exit;

        echo (new Aes())->decrypt($str);exit;

        /*//$str="id=1&ms=45&username=singwa";
        $aes_str='6dDiaoQrSC2tPepBYWGFh8ri8FNeKXBwRFKbn3hv8qA=';

        //echo (new Aes())->encrypt($str);exit;

        echo (new Aes())->decrypt($aes_str);exit;*/
    }

    /**
     * 获取处理的新闻的内容数据
     * @param array $news
     * @return array
     */
    protected function getDealProduct($news = []){
        if (empty($news)){return [];}

        //栏目
        $cats=config('cat.lists');
        //区域
        $adds=config('address.addresslists');

        foreach ($news as $key=>$new){
            $news[$key]['catname']=$cats[$new['catid']]?$cats[$new['catid']] : '-';

            $news[$key]['addressname']=$adds[$new['address']]?$adds[$new['address']] : '-';

        }

        return $news;
    }

    /**
     * 获取分页page size内容
     * @param $data
     */
    public function getPageAndSize($data){
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }

}